import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/nft_pages/order/order_controller.dart';
import 'package:yysk_app/pages/nft_pages/order/order_detail/order_detail_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/card_list_tile_widget.dart';
import 'package:yysk_app/widget/count_down_timer.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/item_card_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';

class OrderIncubationDetailPage extends GetView<OrderDetailController> {
  static const String path = '/orderIncubationDetailPage';
  const OrderIncubationDetailPage({super.key});

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      backgroundColor: AppColors.backgroundColorBlack,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: ImageAssetWidget(
              width: 375.px,
              height: 812.px,
              imageUrl: 'static/images/bg.png',
            ),
          ),
          Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  child: Column(
                    children: [
                      SizedBox(height: top),
                      CustomAppBar2(
                        title: '',
                        context: context,
                        beforBack: () {
                          try {
                            OrderController orderController = Get.find();
                            if (controller.type == 'buyIn') {
                              orderController.getBuyIncubationOrder().then((
                                res,
                              ) {
                                Get.back();
                              });
                            } else {
                              orderController.getSaleOrder().then((res) {
                                Get.back();
                              });
                            }
                          } catch (e) {
                            if (Navigator.canPop(context)) {
                              Get.back();
                            } else {
                              Get.offAllNamed(MainPage.path);
                            }
                          }
                        },
                      ),
                      Column(
                        children: [
                          Obx(() {
                            return controller
                                            .incubationOrderDetail
                                            .value
                                            ?.orderStatus ==
                                        'WAITING_PAY' &&
                                    controller.type != 'sale'
                                ? Column(
                                  children: [
                                    _buildStatusInfo(context: context),
                                    hiSpace(height: 51.px),
                                  ],
                                )
                                : SizedBox();
                          }),
                          Container(
                            padding: EdgeInsets.fromLTRB(12.px, 0, 12.px, 0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Obx(() {
                                  return _buildOrderCollectionInfo();
                                }),
                                hiSpace(height: 8.px),
                                Obx(() {
                                  return Container(
                                    padding: EdgeInsets.all(12.px),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(
                                        10.px,
                                      ),
                                      color: AppColors.backgroundColorGrey2,
                                    ),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          '订单信息',
                                          style: TextStyle(
                                            fontSize: 14.px,
                                            color: AppColors.fontColor,
                                            fontWeight: FontWeight.normal,
                                          ),
                                        ),
                                        _buildOrderDetail(),
                                      ],
                                    ),
                                  );
                                }),
                                Obx(() {
                                  return controller
                                              .incubationOrderDetail
                                              .value
                                              ?.orderStatus ==
                                          'PAY_SUCCESS'
                                      ? Container(
                                        constraints: BoxConstraints(
                                          minWidth: context.width - 24.px,
                                        ),
                                        padding: EdgeInsets.all(12.px),
                                        margin: EdgeInsets.only(top: 8.px),
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(
                                            10.px,
                                          ),
                                          color: AppColors.backgroundColorGrey2,
                                        ),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              '藏品编号',
                                              style: TextStyle(
                                                fontSize: 14.px,
                                                color: AppColors.fontColor,
                                                fontWeight: FontWeight.normal,
                                              ),
                                            ),
                                            hiSpace(height: 20.px),
                                            controller
                                                        .incubationOrderDetail
                                                        .value !=
                                                    null
                                                ? (controller
                                                        .incubationOrderDetail
                                                        .value!
                                                        .tokenIdList!
                                                        .isNotEmpty
                                                    ? Wrap(
                                                      children: [
                                                        ...controller
                                                            .incubationOrderDetail
                                                            .value!
                                                            .tokenIdList!
                                                            .map(
                                                              (item) =>
                                                                  _buildOrderCode(
                                                                    item,
                                                                  ),
                                                            ),
                                                      ],
                                                    )
                                                    : Center(
                                                      child: Column(
                                                        children: [
                                                          Image(
                                                            width: 174.px,
                                                            height: 133.px,
                                                            image: AssetImage(
                                                              'static/images/no_data.png',
                                                            ),
                                                            fit: BoxFit.cover,
                                                          ),
                                                          SizedBox(
                                                            height: 20.px,
                                                          ),
                                                          Text(
                                                            '藏品正在上链中',
                                                            style: TextStyle(
                                                              color:
                                                                  AppColors
                                                                      .fontColorA,
                                                              fontSize: 12.px,
                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                    ))
                                                : Text(''),
                                          ],
                                        ),
                                      )
                                      : SizedBox();
                                }),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  _buildOrderCode(item) {
    return Container(
      margin: EdgeInsets.only(right: 20.px, bottom: 10.px),
      child: Text(
        '# ${item}',
        style: TextStyle(fontSize: 12.px, color: AppColors.fontColorGrayE8),
      ),
    );
  }

  _buildStatusType() {
    final detail = controller.incubationOrderDetail.value;

    switch (detail?.orderStatus) {
      case 'WAITING_PAY':
        return '待支付';
      case 'PAYING':
        return '支付中';
      case 'PAY_SUCCESS':
        return '已完成';
      case 'CANCELLED':
        return '已取消';
      case 'PAY_TIMEOUT':
        return '已取消';
      case 'FAILED':
        return '已取消';
      default:
        return '';
    }
  }

  _payName(data) {
    switch (data) {
      case 'ALIPAY':
        return '支付宝';
      case 'WECHAT':
        return '微信支付';
      case 'REMAINDER':
        return '系统钱包';
      case 'YJZF':
        return '易宝一键支付';
      case 'WALLET_PAY':
        return '易宝钱包支付';
      case 'HNA_PAY':
        return '汇付支付';
      case 'ZERO_PAY':
        return '零元订单';
      case 'DEBIT_CARD':
        return '汇付快捷支付';
      case 'DIN_PAY':
        return '智付支付';
      default:
        return '余额';
    }
  }

  Widget _buildOrderDetail() {
    final detail = controller.incubationOrderDetail.value;
    final status = controller.incubationOrderDetail.value?.orderStatus;
    if (status == 'WAITING_PAY' || status == 'PAYING') {
      return ItemCardWidget(
        backgroundColor: AppColors.backgroundColorGrey2,
        child: Column(
          children: [
            CardListTileWidget(label: '出售价', value: '￥${detail?.payPrice}'),
            CardListTileWidget(label: '数量', value: '*${detail?.count}'),
            CardListTileWidget(label: '订单状态', value: _buildStatusType()),
            CardListTileWidget(label: '下单时间', value: '${detail?.createTime}'),
            CardListTileWidget(
              label: '订单编号',
              value: '${detail?.orderCode}',
              canCopy: true,
            ),
          ],
        ),
      );
    } else if (status == 'PAY_SUCCESS') {
      return ItemCardWidget(
        backgroundColor: AppColors.backgroundColorGrey2,
        child: Column(
          children: [
            CardListTileWidget(label: '成交价', value: '￥${detail?.payPrice}'),
            controller.type == 'sale'
                ? CardListTileWidget(
                  label: '交易手续费',
                  value: '￥${detail?.serviceCharge}',
                )
                : SizedBox(),
            controller.type == 'sale'
                ? CardListTileWidget(
                  label: '收益扣减',
                  value: '￥${detail?.platformEarnings}',
                )
                : SizedBox(),
            controller.type == 'sale'
                ? CardListTileWidget(
                  label: '到账金额',
                  value: '￥${detail?.receivedAmount}',
                )
                : SizedBox(),
            CardListTileWidget(label: '数量', value: '*${detail?.count}'),
            CardListTileWidget(label: '支付方式', value: _payName(detail?.payType)),
            CardListTileWidget(label: '订单状态', value: _buildStatusType()),
            CardListTileWidget(label: '创建时间', value: '${detail?.createTime}'),
            CardListTileWidget(label: '完成时间', value: detail?.payTime ?? '暂无数据'),
            CardListTileWidget(
              label: '订单编号',
              value: '${detail?.orderCode}',
              canCopy: true,
            ),
          ],
        ),
      );
    } else {
      return ItemCardWidget(
        backgroundColor: AppColors.backgroundColorGrey2,
        child: Column(
          children: [
            CardListTileWidget(label: '出售价', value: '￥${detail?.payPrice}'),
            CardListTileWidget(label: '数量', value: '*${detail?.count}'),
            CardListTileWidget(
              label: '订单状态',
              value: detail?.orderStatus == 'CANCELLED' ? '手动取消' : '订单超时',
            ),
            CardListTileWidget(label: '创建时间', value: '${detail?.createTime}'),
            CardListTileWidget(label: '取消时间', value: '${detail?.closeTime}'),
            CardListTileWidget(
              label: '订单编号',
              value: '${detail?.orderCode}',
              canCopy: true,
            ),
          ],
        ),
      );
    }
  }

  // 藏品信息
  Widget _buildOrderCollectionInfo() {
    final item = controller.incubationOrderDetail.value;
    return Container(
      padding: EdgeInsets.all(12.px),
      decoration: BoxDecoration(
        color: AppColors.backgroundColorGrey2,
        borderRadius: BorderRadius.circular(10.px),
      ),
      child: Row(
        children: [
          Row(
            children: [
              LazyImage(
                imageUrl: '${item?.coverImageUrl}',
                width: 44.px,
                height: 44.px,
                borderRadius: 6.px,
              ),
              hiSpace(width: 10.px),
              SizedBox(
                height: 44.px,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    SizedBox(
                      width: 240.px,
                      child: Text(
                        '${item?.collectionName}',
                        style: TextStyle(
                          fontSize: 14.px,
                          color: AppColors.fontColor,
                          fontWeight: FontWeight.normal,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    SizedBox(
                      width: 240.px,
                      child: Text(
                        '${item?.daoName}',
                        style: TextStyle(
                          fontSize: 12.px,
                          color: AppColors.fontColorGray99,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatusInfo({required BuildContext context}) {
    return Obx(() {
      return Container(
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(10.px)),
        margin: EdgeInsets.only(top: 12.px),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '应付金额',
              style: TextStyle(
                fontSize: 12.px,
                color: AppColors.fontColorGray99,
              ),
            ),
            hiSpace(height: 12.px),
            RichText(
              text: TextSpan(
                children: [
                  // TextSpan(
                  //   text: '￥',
                  //   style: TextStyle(
                  //     fontSize: 24.px,
                  //     color: AppColors.fontColorError,
                  //     fontWeight: FontWeight.w500,
                  //   ),
                  // ),
                  TextSpan(
                    text:
                        '${controller.incubationOrderDetail.value?.payPrice ?? '0.00'}',
                    style: TextStyle(
                      color: AppColors.fontColorError,
                      fontSize: 40.px,
                      fontWeight: FontWeight.w500,
                      fontFamily: 'CustomBebas',
                    ),
                  ),
                ],
              ),
            ),
            hiSpace(height: 12.px),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '剩余支付剩余时间 ',
                  style: TextStyle(
                    fontSize: 12.px,
                    color: AppColors.fontColorGray99,
                    fontWeight: FontWeight.normal,
                  ),
                ),
                CountdownTimer(
                  onPressed: () {
                    controller.getIncubationOrderDetail();
                  },
                  fontSize: 12.px,
                  fontWeight: FontWeight.normal,
                  // expireTime:
                  //     (DateTime.now().millisecondsSinceEpoch +
                  //         5000), // 替换为实际的过期时间戳
                  expireTime:
                      (controller.incubationOrderDetail.value?.cancelTime ?? 0),
                ),
              ],
            ),
            hiSpace(height: 28.px),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ButtonWidget(
                  label: '取消订单',
                  width: 104.px,
                  height: 31.px,
                  fontSize: 12.px,
                  bgColorStart: AppColors.backgroundColorGreyF8,
                  bgColorEnd: AppColors.backgroundColorGreyF8,
                  borderRadius: 20,
                  fontColor: AppColors.fontColor,
                  onPressed: () {
                    _showCancleSheet(context: context);
                  },
                ),
                hiSpace(width: 11.px),
                ButtonWidget(
                  label: '继续支付',
                  width: 104.px,
                  height: 31.px,
                  borderRadius: 20,
                  fontSize: 12.px,
                  onPressed: () {
                    controller.getIncubationPayToken(
                      controller.incubationOrderDetail.value?.id!,
                      controller.incubationOrderDetail.value?.productType!,
                    );
                  },
                ),
              ],
            ),
          ],
        ),
      );
    });
  }

  _showCancleSheet({required BuildContext context}) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: AppColors.backgroundColorBlackLight,
          child: Padding(
            padding: EdgeInsets.fromLTRB(22.px, 22.px, 22.px, 16.px),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Center(
                  child: Text(
                    '温馨提示',
                    style: TextStyle(
                      fontSize: 20.px,
                      color: AppColors.fontColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                hiSpace(height: 16.px),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '为维护市场秩序，请尽快完成支付。',
                    style: TextStyle(
                      fontSize: 16.px,
                      color: AppColors.fontColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                hiSpace(height: 12.px),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '当天下单3次未支付，系统会判断为恶意锁单，并限制您当天继续交易，以示惩戒。',
                    style: TextStyle(
                      fontSize: 16.px,
                      color: AppColors.fontColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                hiSpace(height: 12.px),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '3小时后自动解除限制，情节严重者，平台有权对其账号永久封禁。',
                    style: TextStyle(
                      fontSize: 16.px,
                      color: AppColors.fontColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                hiSpace(height: 36.px),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    ButtonWidget(
                      label: '不取消',
                      width: 111.px,
                      height: 36.px,
                      fontSize: 14.px,
                      bgColorStart: AppColors.backgroundColorGreyF8,
                      bgColorEnd: AppColors.backgroundColorGreyF8,
                      fontColor: AppColors.fontColor,
                      borderRadius: 18,
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                    ButtonWidget(
                      label: '确认取消',
                      width: 111.px,
                      height: 36.px,
                      fontSize: 14.px,
                      onPressed: () {
                        controller.cancelOrder();
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
